const {huaweiCloudParams} = require('./configParams')
const {BasicCredentials, Region} = require('@huaweicloud/huaweicloud-sdk-core')
const {
    ShowAssetDetailRequest,
    VodClient,
    CreateAssetByFileUploadReq,
    CreateAssetByFileUploadRequest,
    ConfirmAssetUploadReq,
    ConfirmAssetUploadRequest,
    ConfirmAssetUploadReqStatusEnum
} = require('@huaweicloud/huaweicloud-sdk-vod')

const axios = require('axios')
const request = axios.default.create({
    maxContentLength: Infinity
})

class HuaweiCloud {
    static getVodClient() {
        // 使用永久AK、SK Region级服务
        const auth = new BasicCredentials()
            .withAk(huaweiCloudParams.AK)
            .withSk(huaweiCloudParams.SK)
            .withProjectId(huaweiCloudParams.PROJECT_ID)
        // 初始化指定云服务的客户端
        return VodClient.newBuilder()
            .withCredential(auth)
            .withRegion(new Region(huaweiCloudParams.REGION, huaweiCloudParams.ENDPOINT))
            .build()
    }

    // 获取视频播放地址
    static async getVideoUrl(assetId) {
        let vodClient = HuaweiCloud.getVodClient()
        let detailRequest = new ShowAssetDetailRequest()
        detailRequest.withAssetId(assetId)
        let detail = await vodClient.showAssetDetail(detailRequest)
        let outputs = detail.transcode_info?.output
        if (!outputs || outputs.length <= 0) return ['']
        let urlList = []
        for (let output of outputs) {
            let {bit_rate, duration, video_size} = output.meta_data
            bit_rate > 0 && duration && duration > 0 && video_size > 0 && urlList.push(output.url)
        }
        return urlList
    }

    // 上传视频
    static async uploadVideo({fileBuffer, name, type}) {
        // 获取华为云视频点播客户端
        let vodClient = HuaweiCloud.getVodClient()
        // 创建文件上传请求
        let uploadReq = new CreateAssetByFileUploadReq()
        let uploadRequest = new CreateAssetByFileUploadRequest()
        // 设置视频类型、名称和标题
        uploadReq.withVideoType(type.split('/').pop().toUpperCase()).withVideoName(name).withTitle(name)
        // 设置请求体
        uploadRequest.withBody(uploadReq)
        // 创建文件上传任务，获取临时令牌
        let tempObs = await vodClient.createAssetByFileUpload(uploadRequest)
        // 获取资源ID
        let assetId = tempObs.asset_id
        // 获取文件上传地址
        let videoUploadUrl = tempObs.video_upload_url
        // 上传文件
        let {status} = await request.put(videoUploadUrl, fileBuffer, {
            headers: {'Content-Type': type}
        })
        // 如果上传文件失败，返回错误信息
        if (status !== 200) {
            console.error('上传视频失败')
            return
        }
        // 创建文件确认请求
        let confirmReq = new ConfirmAssetUploadReq()
        let confirmRequest = new ConfirmAssetUploadRequest()
        // 设置文件状态和资源ID
        confirmReq.withStatus(ConfirmAssetUploadReqStatusEnum.CREATED).withAssetId(assetId)
        // 设置请求体
        confirmRequest.withBody(confirmReq)
        // 确认文件上传
        await vodClient.confirmAssetUpload(confirmRequest)
        // 返回资源ID
        return assetId
    }
}

module.exports = HuaweiCloud
